<?php
/*
 * @Description    : 
 * @Author         : QianLong
 * @Date           : 2022-07-17 19:10:36
 * @LastEditors    : QianLong
 * @Site           : http://21ds.cn
 * @LastEditTime   : 2024-03-21 15:40:35
 */

namespace app\api\controller;

use think\facade\Validate;
use think\facade\Db;
use app\lib\Result;

class App extends Base
{
  /**
   * 列表
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://www.21ds.cn/
   */
  public function version_list()
  {
    $rule = [
      'pageNo'  => 'number',
      'pageSize'  => 'number',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'app_id' => input('param.app_id', '', 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    if (empty($data['app_id'])) {
      return Result::Success([], 'APP必须选择');
    }
    $siteInfo = Db::connect('mongodb')->name('app_list')->where('_id', $data['app_id'])->find();
    if (!$siteInfo) {
      return Result::Error('APP不存在或已删除');
    }
    // 构建查询条件
    $where = [];
    $where[] = ['app_id','=',$data['app_id']];
    $where[] = ['uid','=', $this->uid];
    if (!empty($data['title'])) {
      $where[] = ['_id|title', 'like', $data['title']];
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = Db::connect('mongodb')->name('app_version')->where($where)->order('create_time', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
    $totalcount = Db::connect('mongodb')->name('app_version')->where($where)->count('_id');
    foreach ($dataList as &$vo) {
      $vo['create_time'] = date('Y-m-d H:i:s', $vo['create_time']);
      if (isset($vo['upgrade_type']) && !empty($vo['upgrade_type'])) {
        if ($vo['upgrade_type'] == 'all') {
          $vo['version_incr'] = '';
        }else{
          $vo['version_no_android'] = '';
          $vo['version_no_ios'] = '';
        }
      }
      $vo['status'] = ($vo['status'] == 1) ? true : false;
      $vo['force'] = ($vo['force'] == 1) ? true : false;
      unset($vo['delete_time'], $vo['only_hour'], $vo['date']);
    }
    $returnData['data'] = $dataList;
    $returnData['totalCount'] = $totalcount;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public function app_list()
  {
    $rule = [
      'pageNo'  => 'number',
      'pageSize'  => 'number',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    $where = [];

    if (!empty($data['title'])) {
      $where[] = ['title|_id', 'like', $data['title']];
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $serverList = Db::connect('mongodb')->name('file_server_list')->field('_id,title')->where('status', 1)->select()->toArray();
    $serverListArr = [];
    foreach ($serverList as &$vo) {
      $serverListArr[$vo['_id']] = $vo['title'];
    }
    $cateList = Db::connect('mongodb')->name('file_cate')->field('_id,title')->where('status', 1)->select()->toArray();
    $cateListArr = [];
    foreach ($cateList as &$vo) {
      $cateListArr[$vo['_id']] = $vo['title'];
    }
    $dataList = Db::connect('mongodb')->name('app_list')->where($where)->order('create_time', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
    $totalcount = Db::connect('mongodb')->name('app_list')->where($where)->count('_id');
    foreach ($dataList as &$vo) {
      $vo['create_time'] = date('Y-m-d H:i:s', $vo['create_time']);
      $vo['fs_title'] = isset($serverListArr[$vo['fs_id']]) ? $serverListArr[$vo['fs_id']] : '';
      $vo['fc_title'] = isset($cateListArr[$vo['fc_id']]) ? $cateListArr[$vo['fc_id']] : '';
    }
    $returnData['data'] = $dataList;
    $returnData['totalCount'] = $totalcount;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public function editAppInfo()
  {
    if (request()->isPost()) {
      $rule = [
        'title|标题'  => 'require|max:128',
        'status|状态'  => 'require',
        'server_secret|SecretKey'  => 'require',
      ];
      $data = [
        'id' => input('param._id', '', 'trim'),
        'title' => input('param.title', '', 'trim'),
        'status' => input('param.status', '', 'trim'),
        'server_secret' => input('param.server_secret', '', 'trim'),
        'desc' => input('param.desc', '', 'trim'),
        'fs_id' => input('param.fs_id', '', 'trim'),
        'scheme' => input('param.scheme', '', 'trim'),
        'bg_pic' => input('param.bg_pic', '', 'trim'),
        'bg_type' => input('param.bg_type', '0', 'trim'),
        'icon' => input('param.icon', '', 'trim'),
        'btn_color' => input('param.btn_color', '', 'trim'),
        'fc_id' => input('param.fc_id', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      $limitCount = Db::connect('mongodb')->name('app_list')->count();
      // $this->security::checkVersionLimit($this->user['version'], 'log_site_num', '日志APP数量', $limitCount);
      $data['status'] = intval($data['status']);
      $data['bg_type'] = intval($data['bg_type']);
      $this->redis->del('dever:app:info:' . $data['id'], 'full');
      if (!empty($data['id'])) {
        $status = Db::connect('mongodb')->name('app_list')->where('_id', $data['id'])->update($data);
        $tag = '编辑';
      } else {
        unset($data['id']);
        $data['create_time'] = time();
        $data['uid'] = $this->uid;
        $data['username'] = $this->username;
        $data['_id'] = createId('APP');
        $status = Db::connect('mongodb')->name('app_list')->insert($data);
        $tag = '新增';
      }
      if ($status > 0) {
        return json(['code' => 200, 'data' => '', 'msg' => $tag . '成功']);
      } else {
        return json(['code' => -1, 'data' => '', 'msg' => $tag . '失败，请重试']);
      }
    }
  }
  public function editVersionInfo()
  {
    if (request()->isPost()) {
      $rule = [
        'upgrade_title|更新标题'  => 'require',
        'platform|平台类型'  => 'require',
        'notice_cycle|提醒周期'  => 'require',
        'app_id|APP'  => 'require',
        'upgrade_content|更新内容'  => 'require',
        'upgrade_type|更新类型'  => 'require',
        'version_type|版本类型'  => 'require',
      ];
      $data = [
        'platform' => input('param.platform/a', '', 'trim'),
        'id' => input('param._id', '', 'trim'),
        'upgrade_type' => input('param.upgrade_type', '', 'trim'),
        'notice_cycle' => input('param.notice_cycle', '', 'trim'),
        'app_id' => input('param.app_id', '', 'trim'),
        'upgrade_title' => input('param.upgrade_title', '', 'trim'),
        'version_type' => input('param.version_type', '', 'trim'),
        'upgrade_content' => input('param.upgrade_content', '', 'trim'),
        'desc' => input('param.desc', '', 'trim'),
        'version_incr' => input('param.version_incr', '', 'trim'),
        'incr_url' => input('param.incr_url', '', 'trim'),
        'version_no_android' => input('param.version_no_android', '', 'trim'),
        'url_android' => input('param.url_android', '', 'trim'),
        'store_url_android' => input('param.store_url_android', '', 'trim'),
        'version_no_ios' => input('param.version_no_ios', '', 'trim'),
        'url_ios' => input('param.url_ios', '', 'trim'),
        'force' => input('param.force', '', 'trim'),
        'status' => input('param.status', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      $limitCount = Db::connect('mongodb')->name('app_version_' . $this->uid)->count();
      // $this->security::checkVersionLimit($this->user['version'], 'log_site_num', '日志APP数量', $limitCount);
      $data['ios_store_id'] = '';
      if (!empty($data['url_ios'])) {
        preg_match("/id(\d+)/", $data['url_ios'], $matches);
        if (!isset($matches[1]) || empty($matches[1])) {
          return Result::Error('您输入的IOS链接疑似不正确，请确认后重试');
        }
        $data['ios_store_id'] = $matches[1];
      }
      $data['status'] = ($data['status'] === 'true' || $data['status'] === true || $data['status'] === '1' || $data['status'] === 1)?1:0;
      $data['force'] = ($data['force'] === 'true' || $data['force'] === true || $data['force'] === '1' || $data['force'] === 1)?1:0;
      $data['version_no_android'] = intval($data['version_no_android']);
      $data['version_no_ios'] = intval($data['version_no_ios']);
      $data['notice_cycle'] = intval($data['notice_cycle']);
      $this->redis->del('dever:app:version:' . $data['id'], 'full');
      if (!empty($data['id'])) {
        $status = Db::connect('mongodb')->name('app_version_' . $this->uid)->where('_id', $data['id'])->update($data);
        $tag = '编辑';
      } else {
        unset($data['id']);
        $data['create_time'] = time();
        $data['uid'] = $this->uid;
        $data['username'] = $this->username;
        $data['_id'] = createId('AV');
        $status = Db::connect('mongodb')->name('app_version_' . $this->uid)->insert($data);
        $data['id'] = $data['_id'];
        $tag = '新增';
      }
      if ($status > 0) {
        if ($data['status'] === 1) {
          Db::connect('mongodb')->name('app_version_' . $this->uid)->where('app_id', $data['app_id'])->where('upgrade_type', $data['upgrade_type'])->where('version_type', $data['version_type'])->whereNotIn('_id', $data['id'])->update(['status' => 0]);
        }
        return json(['code' => 200, 'data' => $data, 'msg' => $tag . '成功']);
      } else {
        return json(['code' => -1, 'data' => $data, 'msg' => $tag . '失败，请重试']);
      }
    }
  }
  public function changeForceVersion()
  {
    if (request()->isPost()) {
      $rule = [
        'id|APP版本ID'  => 'require',
      ];
      $data = [
        'id' => input('param.id', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return Result::Error($validate->getError());
      }
      $hasVersion = Db::connect('mongodb')->name('app_version_' . $this->uid)->where('_id', $data['id'])->find();
      if (empty($hasVersion)) {
        return Result::Error('版本不存在或异常');
      }
      $update['force'] = $hasVersion['force'] == 1 ? 0 : 1;
      Db::connect('mongodb')->name('app_version_' . $this->uid)->where('_id', $data['id'])->update($update);
      $this->redis->del('dever:app:version:' . $data['id'], 'full');
      return Result::Success('','设置成功');
    }
  }
  public function changeStatusVersion()
  {
    if (request()->isPost()) {
      $rule = [
        'id|APP版本ID'  => 'require',
      ];
      $data = [
        'id' => input('param.id', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return Result::Error($validate->getError());
      }
      $hasVersion = Db::connect('mongodb')->name('app_version_' . $this->uid)->where('_id', $data['id'])->find();
      if (empty($hasVersion)) {
        return Result::Error('版本不存在或异常');
      }
      $update['status'] = $hasVersion['status'] == 1 ? 0 : 1;
      if ($update['status'] == 0) {
        return Result::Error('必须保留一个线上版本，如需启用其他版本，直接将对应版本状态调整为启用即可');
      }
      Db::connect('mongodb')->name('app_version_' . $this->uid)->where('app_id', $hasVersion['app_id'])->where('upgrade_type', $hasVersion['upgrade_type'])->where('version_type', $hasVersion['version_type'])->update(['status'=>0]);
      Db::connect('mongodb')->name('app_version_' . $this->uid)->where('_id', $data['id'])->where('upgrade_type', $hasVersion['upgrade_type'])->where('version_type', $hasVersion['version_type'])->update($update);
      $this->redis->del('dever:app:version:' . $data['id'], 'full');
      return Result::Success('', '设置成功');
    }
  }
  public function del_app()
  {
    $rule = [
      '_id'  => 'require',
    ];
    $data = [
      '_id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $infoData = Db::connect('mongodb')->name('app_list')->field('_id')->where('_id', $data['_id'])->find();
    if (empty($infoData)) {
      return json(['code' => -1, 'data' => '', 'msg' => '内容不存在或网络异常，请稍后重试']);
    }
    $status = Db::connect('mongodb')->name('app_list')->where('_id', $data['_id'])->delete();
    Db::connect('mongodb')->name('app_version')->where('app_id', $data['_id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function del_app_batch()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.ids/a', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $status = Db::connect('mongodb')->name('app_list')->whereIn('_id', $data['id'])->delete();
    Db::connect('mongodb')->name('app_version')->whereIn('app_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function del_version()
  {
    $rule = [
      '_id'  => 'require',
    ];
    $data = [
      '_id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $status = Db::connect('mongodb')->name('app_version')->where('_id', $data['_id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function del_version_all()
  {
    $rule = [
      'app_id'  => 'require',
      'type|清空类型'  => 'require',
    ];
    $data = [
      'app_id' => input('param.app_id', '', 'trim'),
      'type' => input('param.type', '', 'trim'),
      'send_time_ranges' => input('param.send_time_ranges/a', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    if ($data['type'] == 'all') {
      $status = Db::connect('mongodb')->name('app_version')->where('app_id', $data['app_id'])->delete();
    } else {
      $start_time = strtotime($data['send_time_ranges'][0]);
      $end_time = strtotime($data['send_time_ranges'][1]);
      if ($end_time - $start_time > 86400 * 90) {
        return Result::Error('时间跨度不能大于90天');
      }
      $status = Db::connect('mongodb')->name('app_version')->where('app_id', $data['app_id'])->whereBetweenTime('create_time', $start_time, $end_time)->delete();
    }
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function del_version_batch()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.ids/a', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $status = Db::connect('mongodb')->name('app_version')->whereIn('_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
}
